import axios from 'axios'
import cookie from 'cookie'
import cookies from 'js-cookie'

const inBrowser = typeof window !== 'undefined'
const accessKey = 'accessKey'
const expires = 'expires'

export const setToken = (data) => {
  if (process.SERVER_BUILD) return
  let date = new Date()
  date.setSeconds(date.getSeconds() + data.expires_in)
  // date.setSeconds(date.getSeconds() + 20)
  data.expiresSeconds = date.getTime()
  window.localStorage.setItem('token', JSON.stringify(data))
  cookies.set(accessKey, data.access_token, { expires: date })
  cookies.set(expires, date.getTime(), { expires: date })
  setAuthHeader()
}

export const unsetToken = () => {
  if (process.SERVER_BUILD) return
  // window.localStorage.removeItem('token')
  window.localStorage.clear()
  cookies.remove(accessKey)
  cookies.remove(expires)
  window.localStorage.setItem('logout', Date.now())
  setAuthHeader()
}

export const getUserInSSR = (req) => {
  return getTokenInSSR(req)
}

export const getTokenInSSR = (req) => {
  let token = getTokenFromCookie(req) || getTokenFromSession(req)
  // nebula:sess
  if (token[expires] === undefined) {
    return null
  }
  let timestamp = token[expires]
  console.log(new Date().getTime())
  console.log(timestamp)
  console.log('是否超时:' + (new Date().getTime() > timestamp))
  if (new Date().getTime() < timestamp) {
    return token[accessKey] ? token[accessKey] : null
  } else {
    unsetToken()
    return null
  }
}

export const getTokenFromSession = (req) => {
  if (req && req.session) {
    return req.session.accessKey
  }
}

export const getTokenFromCookie = (req) => {
  const cookieStr = inBrowser ? document.cookie : req.headers.cookie
  const cookies = cookie.parse(cookieStr || '') || {}
  return cookies
}

export const getUserFromLocalStorage = () => {
  const json = getTokenFromLocalStorage()
  return json
}

export const getTokenFromLocalStorage = () => {
  if (window.localStorage && window.localStorage.token) {
    let token = JSON.parse(window.localStorage.token)
    if (new Date().getTime() >= token.expiresSeconds) {
      unsetToken()
      return
    }
    return token ? token.access_token : null
  }
}

export const setAuthHeader = (req) => {
  // axios.defaults.headers.common['Authorization'] = 'Bearer 4f5c39f3-2145-4cba-9ec8-fa52912aee61'
  let accessKey = inBrowser ? getTokenFromLocalStorage() : getTokenInSSR(req)
  if (accessKey) {
    axios.defaults.headers.common['Authorization'] = 'Bearer ' + accessKey
  } else {
    delete axios.defaults.headers.common['Authorization']
  }
}
